<template>
  <div class='sub-category'>
    <div class="container">
      <!-- 面包屑 -->
      <SubBread />
      <!-- 筛选区展示 -->
      <SubFilter @fliterChange=fliterChange />
      <!-- 结果区域 -->
      <div class="goods-list" @click="getData">
        <!-- 排序 -->
        <SubSort @sort-change="sortChange" />
        <!-- 列表 -->
        <ul>
          <li v-for="goods in goodsList" :key="goods.id">
            <GoodsItem :goods="goods" />
          </li>
        </ul>
        <!-- 数据缓加载 -->
        <XtxInfiniteLoading :loading="loading" :finished="finished" @infinite="getData()"></XtxInfiniteLoading>
      </div>
    </div>
  </div>
</template>
<script  lang="ts" setup>
import { ref, watch, } from 'vue'
import { useRoute } from 'vue-router'
import SubBread from './sub-bread.vue'
import SubFilter from './sub-filter.vue'
import SubSort from './sub-sort.vue';
import GoodsItem from './goods-item.vue'
import { findSubCategoryGoods } from '../../api/category'
// 数据缓加载逻辑
// 控制加载中
const loading = ref(false)
// 控制加载完成
const finished = ref(false)
// 存放缓加载数据列表的容器
const goodsList = ref([])
const route = useRoute()
// 发起数据请求的使用参数
// 查询参数
let reqParams = {
  page: 1,
  pageSize: 20,
  categoryId: null
}
// 发起获取数据事件
const getData = () => {
  loading.value = true
  reqParams.categoryId = route.params.id
  findSubCategoryGoods(reqParams).then((data: any) => {
    if (data.result.items.length) {
      goodsList.value.push(...data.result.items)
      reqParams.page++
    } else {
      // 加载完毕
      finished.value = true
    }
    // 请求结束
    loading.value = false
  })
}
// 切换二级分类重新加载
watch(() => route.params.id, (newVal) => {
  if (newVal && route.path === ('/category/sub/' + newVal)) {
    goodsList.value = []
    reqParams = {
      page: 1,
      pageSize: 20,
      categoryId: null
    }
    finished.value = false
  }
})

// 更改排序组件的商品筛选结果，重新发送请求
const sortChange = (sortParams) => {
  // 提示数据未加载完毕
  finished.value = false
  // 合并请求参数，保留之前的参数
  reqParams = { ...reqParams, ...sortParams }
  // 重载数据返回第一页
  reqParams.page = 1
  // 并清空原来的数据
  goodsList.value = []
}
// 更改筛选组件的筛选数据，重新请求
const fliterChange = (filterParams) => {
  // 拼接新的筛选条件
  reqParams = { ...reqParams, ...filterParams }
  reqParams.page = 1
  goodsList.value = []
  finished.value = false
}
</script>
<style lang="less"  scoped>
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;

  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;

    li {
      margin-right: 20px;
      margin-bottom: 20px;

      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>